package com.Lixiaoqian.PartyHistoryMuseum.net;


import com.Lixiaoqian.PartyHistoryMuseum.base.MyApplication;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by Werb on 2016/8/18.
 */
public class ApiRetrofit {

    public  BannerApi bannerApi;

    public BannerApi getBannerService() {
        return bannerApi;
    }


    ApiRetrofit(){
        File httpCacheDirectory = new File(MyApplication.getContext().getCacheDir(), "cache");
        Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.cache(cache);
        builder.connectTimeout(8, TimeUnit.SECONDS);
        OkHttpClient okHttpClient = builder
                .addNetworkInterceptor(new CacheInterptor())
                .build();

        Retrofit bannerRetrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                //.addConverterFactory(GsonConverterFactory.create())
                .build();
        bannerApi=bannerRetrofit.create(BannerApi.class);
    }




public class CacheInterptor implements Interceptor{


    @Override
    public Response intercept(Chain chain) throws IOException {
        //拦截Request对象
        Request request = chain.request();
        //判断有无网络连接
        boolean connected = Utils.isNetworkAble();
        if (!connected) {
            //如果没有网络,从缓存获取数据
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
        Response response = chain.proceed(request);

        if (connected) {
            //有网络，缓存时间短
            String cacheControl = request.cacheControl().toString();
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control","public, max-age=90")
                    .build();
        } else {
            //没有网络
            int maxTime = 3600;
            return response.newBuilder()
                    //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                    .header("Cache-Control", "public, max-age=" + maxTime)
                    .removeHeader("Pragma")
                    .build();
        }
    }
}

   /* public NewApi newApiService;
    public UserApi userApiService;
    public ResourceApi resourceService;
    public NaviApi mNaviApi;


    public NewApi getNewApiService() {
        return newApiService;
    }

    public UserApi getUserApiService() {
        return userApiService;
    }

    public ResourceApi getResourceService() {
        return resourceService;
    }
    public NaviApi getNaviService() {
        return mNaviApi;
    }


    ApiRetrofit() {
      *//*  //cache url
        File httpCacheDirectory = new File(App.getContext().getCacheDir(), "getcache");
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(httpCacheDirectory, cacheSize);

        OkHttpClient getCahce = new OkHttpClient.Builder()
                .addNetworkInterceptor(netInterceptor)
                .connectTimeout(15, TimeUnit.SECONDS)//超时时间15S
                .cache(cache).build();
*//*
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10,TimeUnit.SECONDS);
        builder.addNetworkInterceptor(provideCacheInterceptor());
        OkHttpClient postCache = builder.build();

        Retrofit retrofit_user = new Retrofit.Builder()
                .baseUrl(USER_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(postCache)
                .build();
        Retrofit retrofit_news = new Retrofit.Builder()
                .baseUrl(NEW_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(postCache)
                .build();

        Retrofit retrofit_resource = new Retrofit.Builder()
                .baseUrl(RESOURCE_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(postCache)
                .build();
        Retrofit retrofit_NaviApi = new Retrofit.Builder()
                .baseUrl(NAVi_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(postCache)
                .build();



        userApiService = retrofit_user.create(UserApi.class);
        newApiService = retrofit_news.create(NewApi.class);
        resourceService = retrofit_resource.create(ResourceApi.class);
        mNaviApi = retrofit_NaviApi.create(NaviApi.class);
      *//*
        DailyApiService = retrofit_daily.create(DailyApi.class);*//*
    }
    public static Interceptor provideCacheInterceptor ()
    {
        return new Interceptor()
        {
            @Override
            public Response intercept (Chain chain) throws IOException
            {
                Response response = chain.proceed( chain.request() );

                // 正常访问同一请求接口（多次访问同一接口），给30秒缓存，超过时间重新发送请求，否则取缓存数据
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(30, TimeUnit.SECONDS )
                        .build();

                return response.newBuilder()
                        .header("Cache-Control", cacheControl.toString() )
                        .build();
            }
        };
    }
*/
}
